package com.example.springbootdemo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.springbootdemo.entity.User;
import com.example.springbootdemo.exception.BizException;
import com.example.springbootdemo.mapper.UserMapper;
import com.example.springbootdemo.model.TableData;
import com.example.springbootdemo.service.IUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    private UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public TableData<User> getPageData(Integer offset, Integer limit) throws BizException {
//        log.debug(String.format("查询分页数据, 开始索引位置: %s, 每页的数据: %s", offset, limit));
        if(log.isDebugEnabled()) {
            log.debug("查询分页数据, 开始索引位置: {}, 每页的数据: {}", offset, limit);
        }

        TableData<User> tableData = new TableData<>();
        try {
            Page<User> page = PageHelper.offsetPage(offset, limit);
            userMapper.selectList(Wrappers.emptyWrapper());

            tableData.setTotal(page.getTotal());
            tableData.setRows(page.getResult());
        }catch (Exception exception) {
            log.error(exception.getMessage());  //记录日志
            throw new BizException("分页查询异常.");
        }
        return tableData;
    }

    @Override
    public User getUser(Integer id) throws BizException {
        User user = null;
        try {
            user = userMapper.selectById(id);
        }catch (Exception exception) {
            log.error(exception.getMessage());  //记录日志
            throw new BizException("查询用户信息错误");
        }
        return user;
    }
}
